package com.nzw.aop;

import com.nzw.utils.DateTimeUtilT;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by XuZhansi on 2017/9/11.
 */
@Aspect
@Component
public class LogRecord {

    @Pointcut(value = "execution(* com.nzw.controller..*.*(..))")
    public void LogRecord() {}

    @AfterThrowing(pointcut = "LogRecord()",throwing = "e")
   public void afterThrowing(JoinPoint joinPoint,Exception e){
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Map<String,Object> argMap=new HashMap<>();
        String[] strings = methodSignature.getParameterNames();
        Object [] args=joinPoint.getArgs();
        for (int i=0;i<strings.length;i++){
            argMap.put(strings[i],args[i]);
        }
        String now= DateTimeUtilT.dateTime(new Date());
        System.out.println("当前时间："+now+"  出现异常："+e.getClass()+"  ------>  方法名："+joinPoint.getSignature().getName()+" 参数："+argMap);
   }

    @AfterReturning(value = "LogRecord()",returning = "result")
    public void afterMethod(JoinPoint joinPoint,Object result){
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Map<String,Object> argMap=new HashMap<>();
        String[] strings = methodSignature.getParameterNames();
        Object [] args=joinPoint.getArgs();
        for (int i=0;i<strings.length;i++){
            argMap.put(strings[i],args[i]);
        }
        String now= DateTimeUtilT.dateTime(new Date());
        System.out.println("当前时间："+now+"  接收  ------>  方法名："+joinPoint.getSignature().getName()+" 参数："+argMap);
        System.out.println("返回值 <------  "+result);
    }
}
